// UDP Sokect 管理
// Created by kenny on 25-10-20.
//

#ifndef UDP_SOCKET_MANAGER_H
#define UDP_SOCKET_MANAGER_H

#include <stdint.h>
#include <stdbool.h>

#ifdef _WIN32
    #include <winsock2.h>
    typedef SOCKET socket_t;
#else
typedef int socket_t;
#define INVALID_SOCKET (-1)
#define SOCKET_ERROR (-1)
#endif

// 定义回调函数类型
typedef void (*udp_recv_callback_t)(uint8_t* data, uint16_t length, const char* from_ip, int from_port);

// UDP Socket管理器
typedef struct {
    socket_t socket_fd;
    char server_ip[16];
    int server_port;
    bool is_connected;
    bool running;

    // 回调函数
    udp_recv_callback_t recv_callback;

    // 线程相关
#ifdef _WIN32
    HANDLE recv_thread;
#else
    pthread_t recv_thread;
#endif

} mcp_udp_t;

// API函数
int mcp_udp_init(mcp_udp_t* manager, const char* ip, int port,
                           udp_recv_callback_t recv_cb);
int mcp_udp_connect(mcp_udp_t* manager);
int mcp_udp_send(mcp_udp_t* manager, const uint8_t* data, uint16_t length);
int mcp_udp_send_to(mcp_udp_t* manager, const uint8_t* data, uint16_t length,
                              const char* dest_ip, int dest_port);
int mcp_udp_close(mcp_udp_t* manager);
bool mcp_udp_is_connected(mcp_udp_t* manager);
void mcp_udp_cleanup(mcp_udp_t* manager);

#endif // UDP_SOCKET_MANAGER_H
